<template>
  <div class="admin-order-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="订单ID">
        <el-input v-model="queryParams.ordfId" placeholder="请输入订单ID" clearable />
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="queryParams.ordfState" placeholder="请选择订单状态" clearable class="status-select">
          <el-option v-for="item in orderStatusOptions" :key="item.value" :label="item.label" :value="item.value">
            <span class="status-dot" :style="{ backgroundColor: item.color }"></span>
            <span style="margin-left: 8px;">{{ item.label }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
        <el-button icon="Refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量操作按钮 -->
    <div class="batch-actions" style="margin-bottom: 12px;">
      <el-button type="primary" :disabled="!canBatchShip" @click="handleBatchShip">批量发货</el-button>
    </div>

    <!-- 订单表格 -->
    <el-table
      :data="orders"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      :cell-style="{ padding: '10px 0' }"
      :row-key="(row: any) => row.ordfId"
      :selectable="selectableRow"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="ordfId" label="订单ID" min-width="100" />
      <el-table-column prop="ordfCmdtyId" label="商品ID" min-width="100" />
      <el-table-column prop="ordfUserId" label="用户ID" min-width="100" />
      <el-table-column prop="ordfCount" label="购买数量" min-width="80" align="center" />
      <el-table-column prop="ordfTotalAmt" label="总金额" min-width="100" align="right">
        <template #default="scope">
          <span>¥{{ scope.row.ordfTotalAmt.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="ordfState" label="订单状态" min-width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.ordfState)" effect="light" size="small">
            {{ getStatusText(scope.row.ordfState) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="ordfCreatedOn" label="下单时间" min-width="160" />
      <el-table-column prop="ordfLastUpdated" label="最后更新时间" min-width="160" />
      <el-table-column label="操作" min-width="100" align="center">
        <template #default="scope">
          <el-button v-if="scope.row.ordfState === 'PENDING_SHIP'" type="primary" size="small" @click="handleShip(scope.row)">发货</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adgetOrderApi, adupdateOrderApi, getOrderApi, updateOrderApi } from '@/api/order'

// 订单类型
interface Order {
  ordfId: number
  ordfCmdtyId: number
  ordfUserId: number
  ordfCount: number
  ordfTotalAmt: number
  ordfState: 'PENDING_SHIP' | 'PENDING_RECEIVE' | 'RECEIVED'
  ordfCreatedOn: string
  ordfLastUpdated: string
}

// 查询参数
const queryParams = reactive({
  ordfId: '',
  ordfState: '',
  page: 1,
  pageSize: 10
})

const total = ref(0)
const orders = ref<Order[]>([])
const selectedOrders = ref<Order[]>([])

// 状态标签类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING_SHIP': 'warning',
    'PENDING_RECEIVE': 'primary',
    'RECEIVED': 'success'
  }
  return statusMap[status] || 'info'
}

// 状态中文
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING_SHIP': '待发货',
    'PENDING_RECEIVE': '待收货',
    'RECEIVED': '已收货'
  }
  return statusMap[status] || '未知状态'
}

// 查询
const handleSearch = () => {
  queryParams.page = 1
  fetchOrders()
}

// 重置
const handleReset = () => {
  queryParams.ordfId = ''
  queryParams.ordfState = ''
  queryParams.page = 1
  fetchOrders()
}

// 订单多选
const handleSelectionChange = (val: Order[]) => {
  selectedOrders.value = val
}

// 是否可批量发货
const canBatchShip = computed(() =>
  selectedOrders.value.length > 0 && selectedOrders.value.every(o => o.ordfState === 'PENDING_SHIP')
)

// 批量发货
const handleBatchShip = async () => {
  await ElMessageBox.confirm('确定要批量将选中订单设为已发货吗？', '提示', { type: 'warning' })
  for (const order of selectedOrders.value) {
    await handleShip(order, false)
  }
  ElMessage.success('批量发货成功')
  fetchOrders()
}

// 单个发货
const handleShip = async (order: Order, showMsg = true) => {
  // 只传订单数据，不传ordfState
  const { ordfState, ...orderData } = order
  await adupdateOrderApi(orderData)
  if (showMsg) {
    ElMessage.success('发货成功')
    fetchOrders()
  }
}

// 获取订单列表
const fetchOrders = async () => {
  const res = await adgetOrderApi(queryParams)
  if(res.code==200){
    ElMessage.success(res.msg)
    orders.value=res.data.list
    total.value=res.data.total
  }
}

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  fetchOrders()
}
const handleCurrentChange = (val: number) => {
  queryParams.page = val
  fetchOrders()
}

// 只允许PENDING_SHIP状态可多选
const selectableRow = (row: any): boolean => row.ordfState === 'PENDING_SHIP'

const orderStatusOptions = [
  { label: '待发货', value: 'PENDING_SHIP', color: '#e6a23c' },
  { label: '待收货', value: 'PENDING_RECEIVE', color: '#409eff' },
  { label: '已收货', value: 'RECEIVED', color: '#67c23a' }
]

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.admin-order-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}
.search-form {
  margin-bottom: 16px;
}
.batch-actions {
  margin-bottom: 12px;
}
.pagination-container {
  margin-top: 24px;
  padding: 16px 0;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #ebeef5;
}
.status-select {
  width: 160px;
}
.status-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  vertical-align: middle;
}
</style>
